package com.qwer.service.accesscontrol.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.qwer.mapper.accesscontrol.AccFileRepository;
import com.qwer.model.accesscontrol.AccFileInfo;
import com.qwer.service.accesscontrol.AccFileService;

@Service
public class AccFileServiceImpl implements AccFileService{
    
    @Autowired
    private AccFileRepository repository;
    
    

    @Override
    public Page<AccFileInfo> findList(Pageable pageable,AccFileInfo model) {
        
        Specification<AccFileInfo> spec = new Specification<AccFileInfo>() {

            @Override
            public Predicate toPredicate(Root<AccFileInfo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                
                List<Predicate> list = new ArrayList<>();
                if (StringUtils.isNotEmpty(model.getFileName())) {
                    list.add(cb.like(root.get("fileName"),"%"+model.getFileName()+"%"));
                    
                }
                if(null!=model.getUserId()){
                    list.add(cb.equal(root.get("userId"), model.getUserId()));
                }
                Predicate[] p = new Predicate[list.size()];
                return cb.and(list.toArray(p));
            }
            
        };   
        Page<AccFileInfo> orderMasterPage = repository.findAll(spec,pageable);
        
        List<AccFileInfo> orderDTOList = orderMasterPage.getContent();

        return new PageImpl<AccFileInfo>(orderDTOList, pageable, orderMasterPage.getTotalElements());
    }


    @Override
    public void save(AccFileInfo model) {
         repository.save(model);
    }

    @Override
    public void deleteById(Integer id) {
        
         repository.delete(id);;
    }


    @Override
    public AccFileInfo findById(Integer id) {
        return repository.findOne(id);
    }

}
